//
//  MusicController.m
//  Image圆角优化
//
//  Created by 宜必鑫科技 on 2017/11/30.
//  Copyright © 2017年 宜必鑫科技. All rights reserved.
//

#import "MusicController.h"
#import <Speech/Speech.h>
#import <AVFoundation/AVFoundation.h>
#import "AVAudioRecorderManager.h"

@interface MusicController ()<SFSpeechRecognizerDelegate>
@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) UIButton *startBut;
@property (nonatomic, strong) UIButton *localBut;
@property (nonatomic, assign) BOOL isStart;
@end

@implementation MusicController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    ///> 音频的编解码格式  压缩算法 pcm aac mp3 ogg
    /*
        1. pcm编码  以.mav结尾 是文件形式 是一个文件  它是经过 pcm是无损wav文件中音频数据的一种编码方式，但wav还可以用其它方式编码。
        2. aac（高级音频编码） .M4a结尾 用于iOS 有损压缩压缩的质量高体积小
     */
    
    
    ///> 开始录音
    ///> 结束之后  保存在Document文件夹里面
    ///> 然后开始识别
    [self createView];
}

- (void)createView
{
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.backgroundColor = [UIColor whiteColor];
    
    _startBut = [UIButton buttonWithType:UIButtonTypeCustom];
    _startBut.frame = CGRectMake(50, kScreenH - 70 - 64, kScreenW/2 - 60, 50);
    _startBut.backgroundColor = [UIColor grayColor];
    [_startBut setTitle:@"-开始-" forState:0];
    [_startBut addTarget:self action:@selector(onClick) forControlEvents:1<<6];
    [self.view addSubview:_startBut];
    
    _localBut = [UIButton buttonWithType:UIButtonTypeCustom];
    _localBut.frame = CGRectMake(kScreenW/2 + 10, kScreenH - 70 - 64, kScreenW/2 - 60, 50);
    _localBut.backgroundColor = [UIColor grayColor];
    [_localBut setTitle:@"识别本地" forState:0];
    [_localBut addTarget:self action:@selector(recognizeLocal) forControlEvents:1<<6];
    [self.view addSubview:_localBut];
    
    _label = [[UILabel alloc]initWithFrame:CGRectMake(10, 70, kScreenW - 20, kScreenH - 110 - 64 - 70)];
    _label.backgroundColor = [UIColor lightGrayColor];
    _label.text = @"label";
    _label.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:_label];
    
    _timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, kScreenW - 20, 50)];
    _timeLabel.backgroundColor = [UIColor lightGrayColor];
    _timeLabel.text = @"timeLabel";
    _timeLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_timeLabel];
    [AVAudioRecorderManager shareManager].changeTimeStr = ^(NSString *time) {
        _timeLabel.text = time;
    };
}

- (void)onClick
{
    self.isStart = !self.isStart;
    if (self.isStart) {
        [[AVAudioRecorderManager shareManager] startRecorderWithRestlt:^(BOOL isSuccess) {
            if (isSuccess) {
                [_startBut setTitle:@"结束录音" forState:0];
            }else{
                [self showAleart];
            }            
        }];
    }else{
        [[AVAudioRecorderManager shareManager] stopRecorderWithRestlt:^(BOOL isSuccess) {
            if (isSuccess) {
                [_startBut setTitle:@"开始录音" forState:0];
                [self recognizeWith:[AVAudioRecorderManager shareManager].recordURL];
            }else{
                [self showAleart];
            } 
        }];
    }
}

- (void)recognizeLocal
{
    //创建音乐文件路径 遇到的问题来获取到该文件时，一直无法拿到这个文件，解决方法如下
    // 在Build Phases -> Copy Bundle Resources下点击加号（+）
    NSURL *url =[[NSBundle mainBundle] URLForResource:@"录音.m4a" withExtension:nil];
    [self recognizeWith:url];
}

///> 识别
- (void)recognizeWith:(NSURL*)url
{
    if (!url) return;
    NSLocale *local =[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    SFSpeechRecognizer *localRecognizer = [[SFSpeechRecognizer alloc] initWithLocale:local];
    SFSpeechURLRecognitionRequest *res = [[SFSpeechURLRecognitionRequest alloc] initWithURL:url];
    __weak typeof(self) weakSelf = self;
    [localRecognizer recognitionTaskWithRequest:res resultHandler:^(SFSpeechRecognitionResult * _Nullable result, NSError * _Nullable error) {
        if (error) {
            weakSelf.label.text = @"语音识别解析失败";
        }else{
            weakSelf.label.text = result.bestTranscription.formattedString;
        }
        [self playYuYin];
    }];
}

- (void)playYuYin
{
    AVSpeechUtterance *aut = [AVSpeechUtterance speechUtteranceWithString:self.label.text];
    aut.rate = 0.5;
    AVSpeechSynthesizer *sp = [[AVSpeechSynthesizer alloc]init];
    [sp speakUtterance:aut];
}


- (void)showAleart
{
    // 用户不同意获取麦克风
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"麦克风不可用" message:@"请在“设置 - 隐私 - 麦克风”中允许XXX访问你的麦克风" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *openAction = [UIAlertAction actionWithTitle:@"前往开启" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //如果要让用户直接跳转到设置界面，则可以进行下面的操作，如不需要，就忽略下面的代码
        /*
         *iOS10 开始苹果禁止应用直接跳转到系统单个设置页面，只能跳转到应用所有设置页面
         *iOS10以下可以添加单个设置的系统路径，并在info里添加URL Type，将URL schemes 设置路径为prefs即可。
         *@"prefs:root=Sounds"
         */
        NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if([[UIApplication sharedApplication] canOpenURL:url])
            [[UIApplication sharedApplication] openURL:url options:[NSDictionary new] completionHandler:NULL];
    }];
    
    [alertController addAction:openAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    [self dismissViewControllerAnimated:YES completion:NULL];
}
@end
